﻿using System;
using System.Threading;
using System.Windows.Forms;

using DreamCube.WinForm.Common;
using DreamCube.Foundation.Basic.Utility;

namespace DreamCube.TaobaoGJ.UI
{
    public partial class MainForm : Form
    {
        private Boolean isCopying = false;

        public MainForm()
        {
            InitializeComponent();
            Initial();
        }

        private void Initial()
        {
            try
            {
                this.Text = MyConfig.GetAppSettingValue("AppName");
                this.chk_ShowTP.Checked = Convert.ToBoolean(MyConfig.GetAppSettingValue("chk_ShowTP"));
                this.chk_Second.Checked = Convert.ToBoolean(MyConfig.GetAppSettingValue("chk_Second"));
                this.chk_CopyCat.Checked = Convert.ToBoolean(MyConfig.GetAppSettingValue("chk_CopyCat"));
                BLL.SessionKey.GetSessionKey();
                lb_SessionUser.Text = BLL.SessionKey.SessionNick;
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
        }

        /// <summary>
        /// 保存用户的配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveConfig(Object sender, EventArgs e)
        {
            CheckBox ch = sender as CheckBox;
            if (ch != null)
                MyConfig.SetAppSettingValue(ch.Name, ch.Checked.ToString());
        }

        /// <summary>
        /// 开始复制按钮单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //GetSession();
            if (String.IsNullOrEmpty(txt_goodUrls.Text))
            {
                MessageBox.Show("亲，明显你没填写商品Url啊，你让小弟复制什么商品呢？！", "提醒");
                return;
            }
            Thread thread = new Thread(new ThreadStart(() =>
            {
                isCopying = true;
                BeginCopyItem();
                isCopying = false;
            }));
            thread.SetApartmentState(ApartmentState.STA);
            MyControl.SetEnableAllControls(this, false);
            thread.Start();
            if (chk_ShowTP.Checked)
            {
                this.Close();
            }
            else
            {
                MyWaitingForm.Show();
            }
        }

        /// <summary>
        /// 开始复制商品
        /// </summary>
        private void BeginCopyItem()
        {
            String currentGoodUrl = "";
            String errorMsg = "商品【{0}】复制失败！！";
            try
            {
                String[] goodUrls = GetGoodUrls();
                if (goodUrls == null) return;
                Boolean hasGetSession = false;
                String runningMsg = "正在复制第【{0}】个商品！";
                ShowStatus("正在复制...");
                Int32 i = 0;
                if (!BLL.SessionKey.ConfirmSessionKey())
                {
                    //如果获取授权失败，则直接返回，不用执行代码了。
                    if (!GetSession())
                    {
                        isCopying = false;
                        ShowStatus("亲，获取授权失败，请把此问题报告给开发员处理");
                        ReShowForm();
                        return;
                    }
                }
                for (; i < goodUrls.Length; i++)
                {
                    String goodID = null;
                    currentGoodUrl = goodUrls[i];
                    AnalyseItemUrl(goodUrls[i], out goodID);
                    if (!String.IsNullOrEmpty(goodID))
                    {
                        Int64 newGoodItemId = -1;
                        if (!chk_ShowTP.Checked) MyWaitingForm.Show(this, String.Format(runningMsg, (i + 1).ToString()), true);
                        if (!BLL.TB_TopClientFunc.TryCopyItem(Int64.Parse(goodID), chk_Second.Checked, chk_CopyCat.Checked, out newGoodItemId))
                        {
                            if (hasGetSession)
                            {
                                MyControl.ControlInvoke(this, new Action<Object>((o) => { String.Format(toolLabel_Failed.Tag.ToString(), (Int32.Parse(toolLabel_Failed.Text.Replace("个", "")) + 1).ToString()); }), "");
                                MyLog.MakeLog(String.Format(errorMsg, currentGoodUrl));
                                continue;
                            }
                            else
                            {
                                //重复获取一次sessionKey
                                if (!GetSession())
                                {
                                    ShowStatus("亲，复制太频繁了，出错了，请把此问题报告给开发员处理");
                                    break;
                                }
                                BLL.TB_TopClientFunc.TryCopyItem(Int64.Parse(goodID), chk_Second.Checked, chk_CopyCat.Checked, out newGoodItemId);
                            }
                        }
                        else
                        {
                            MyControl.ControlInvoke(this, new Action<Object>((o) => { toolLabel_Success.Text = String.Format(toolLabel_Success.Tag.ToString(), (Int32.Parse(toolLabel_Success.Text.Replace("个", "")) + 1).ToString()); }), "");
                        }
                        MyControl.ControlInvoke(this, new Action<Object>((o) => { String.Format(toolLabel_Wait.Tag.ToString(), goodUrls.Length - i); }), "");
                    }
                }
                if (i == goodUrls.Length)
                {
                    ShowStatus("复制完成！");
                }
                //else
                //{
                //    MyLog.MakeLog(String.Format(errorMsg, currentGoodUrl));
                //    ShowStatus("复制失败！");
                //}
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(String.Format(errorMsg, currentGoodUrl));
                ShowStatus("复制失败！");
                MyLog.MakeLog(ex);
            }
            finally
            {
                isCopying = false;
                MyControl.SetEnableAllControls(this, true);
                MyWaitingForm.Hide();
                if (chk_ShowTP.Checked)
                {
                    MyControl.ControlInvoke(this, new Action<Object>((o) => { this.ReShowForm(); }), "");
                }
            }
        }

        /// <summary>
        /// 显示状态信息
        /// </summary>
        /// <param name="msg"></param>
        private void ShowStatus(String msg)
        {
            MyControl.ControlInvoke(this, new Action<Object>((o) => { toolStripStatusLabel6.Text = msg; }), "");
        }

        /// <summary>
        /// 获取Session值
        /// </summary>
        private Boolean GetSession()
        {
            GetSessionKey getSessionForm = new GetSessionKey();
            DialogResult result = System.Windows.Forms.DialogResult.Cancel;
            MyControl.ControlInvoke(this, new Action<Object>((o) =>
            {
                result = getSessionForm.ShowDialog(this);
                lb_SessionUser.Text = getSessionForm.UserNick;
            }), "");
            if (result == System.Windows.Forms.DialogResult.OK) return true;
            return false;
        }

        /// <summary>
        /// 分析商品的Url，看看是否正常
        /// </summary>
        /// <param name="itemUrl"></param>
        /// <param name="itemID"></param>
        private void AnalyseItemUrl(String itemUrl, out String itemID)
        {
            itemID = String.Empty;
            if (itemUrl.StartsWith("http://item.taobao.com/"))
            {
                String tempStr = MyString.RightOfLast(itemUrl, "id=");
                itemID = MyString.Left(tempStr, "&", false, tempStr);
            }
        }

        /// <summary>
        /// 按下ctrl+A的时候全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_goodUrls_KeyDown(object sender, KeyEventArgs e)
        {
             MyTextBox.TextBoxCtrlA(sender, e);
        }

        /// <summary>
        /// 获取商品的url
        /// </summary>
        /// <returns></returns>
        private String[] GetGoodUrls()
        {
            if (!String.IsNullOrEmpty(this.txt_goodUrls.Text))
            {
                String[] goodUrls = MyString.RemoveRepeatItems(MyString.RemoveNullOrEmptyItems(this.txt_goodUrls.Text.Split(new char[] { '\r' }),
                    new Func<String, String>((sInput) =>
                    {
                        return sInput.Replace(@"\r", "").Replace("\n", "");
                    })), null, null);
                return goodUrls;
            }
            return null;
        }

        /// <summary>
        /// 计算商品数量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_goodUrls_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.txt_goodUrls.Text))
            {
                String[] goodUrls = GetGoodUrls();
                if (goodUrls != null)
                {
                    lb_GoodCount.Text = goodUrls.Length.ToString();
                    toolLabel_Wait.Text = String.Format(toolLabel_Wait.Tag.ToString(), goodUrls.Length.ToString());
                }
            }
        }

        /// <summary>
        /// 更换授权用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            GetSession();
        }

        /// <summary>
        /// 用户最小化的时候隐藏到托盘中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_ClientSizeChanged(object sender, EventArgs e)
        {
            //最小化处理
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                //不在任务栏显示窗体
                this.ShowInTaskbar = false;
            }
        }

        /// <summary>
        /// 用户最小化的时候隐藏到托盘中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //取消关闭逻辑
            e.Cancel = true;
            this.Hide();
        }

        /// <summary>
        /// 退出程序按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 退出程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("你确定要退出月光族软件吗？", "确认", MessageBoxButtons.OKCancel,
                 MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                notifyIcon1.Visible = false;
                this.Close();
                this.Dispose();
                Application.Exit();
            }       
        }

        /// <summary>
        /// 重新显示窗体
        /// </summary>
        private void ReShowForm()
        {
            MyControl.ControlInvoke(this, new Action<Object>((o) =>
            {
                if (!isCopying)
                {
                    this.Show();
                    this.WindowState = FormWindowState.Normal;
                    this.Activate();
                }
            }), "");
        }

        /// <summary>
        /// 双击弹开窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //双击显示
            if (e.Button == MouseButtons.Left)
            {
                ReShowForm();
            }
        }
    }
}
